package org.icec.sms.service;
import org.springframework.stereotype.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

import org.beetl.sql.core.engine.PageQuery;
import org.icec.common.model.BaseModel;
import org.icec.sms.model.SmsRecord;
import org.icec.web.core.sys.model.SysUser;
import org.icec.sms.dao.SmsRecordDao;

/*
* 
* gen by icec  2018-10-29
*/
@Service
public class SmsRecordService   {
	@Autowired
	private SmsRecordDao  smsRecordDao ;
	
	/**
	 * 发送短信（插入到短信表）
	 * @param phone
	 * @param templateCode
	 * @param param
	 * @param optuser
	 */
	public void sendSms(String phone, String templateCode,String param ,SysUser optuser) {
		SmsRecord smsRecord = new SmsRecord(optuser.getId(),SmsRecord.DEL_FLAG_NORMAL,param,phone,SmsRecord.STATE_NO,templateCode,new Date());
		smsRecordDao.insert(smsRecord);
	}
	/**
	*
	*保存
	*/
	@Transactional
	public void save(SmsRecord smsRecord,SysUser optuser){
		smsRecord.setDelFlag(SmsRecord.DEL_FLAG_NORMAL);
		smsRecordDao.insert(smsRecord);
	}
	/**
	*
	*更新
	*/
	@Transactional
	public void update(SmsRecord smsRecord,SysUser optuser){
		 
		smsRecordDao.updateTemplateById(smsRecord);
	}
	/**
	 * 删除操作，更新del_flag字段
	 * 
	 * @param ids
	 * @param optuser
	 */
	@Transactional
	public void deleteAll(String ids,SysUser optuser) {
		String[] idarr = ids.split(",");
		for (String id : idarr) {
			SmsRecord smsRecord = new SmsRecord();
			smsRecord.setId(Integer.parseInt(id));
			smsRecord.setDelFlag(BaseModel.DEL_FLAG_DELETE);
			smsRecordDao.updateTemplateById(smsRecord);
		}

	}
	/**
	 * 一键删除未发送短信
	 * @return
	 */
	@Transactional
	public void deleteSmsWithNoSend() {
		List<SmsRecord> list = smsRecordDao.createLambdaQuery()
		.andEq(SmsRecord::getDelFlag, SmsRecord.DEL_FLAG_NORMAL)
		.andEq(SmsRecord::getState, SmsRecord.STATE_NO).select();
		for(SmsRecord record:list) {
			record.setDelFlag(BaseModel.DEL_FLAG_DELETE);
			smsRecordDao.updateTemplateById(record);
		}
	}
	/**
	*
	*按主键查询
	*
	*/
	public SmsRecord get(Integer id){
		return smsRecordDao.single(id);
	}
	/**
	*
	*分页查询
	*
	*/
	public PageQuery<SmsRecord> pageQuery(PageQuery<SmsRecord> query){
		return smsRecordDao.pageQuery(query);
	}
	
	/**
	 * 根据发送状态查询
	 * @param state
	 * @return
	 */
	public List<SmsRecord> getRecordByState(String state){
		return smsRecordDao.getRecordByState(state);
	}
	
	/**
	 * 发送完成
	 * @param id
	 * @param code
	 */
	@Transactional
	public void sendOk(Integer id,String code) {
		SmsRecord record = new SmsRecord();
		record.setId(id);
		record.setCode(code);
		record.setState(SmsRecord.STATE_YES);
		record.setSendtime(new Date());
		smsRecordDao.updateTemplateById(record);
	}
}
